package org.cwnuit.train.acton;

import java.io.IOException;
import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.cwnuit.train.domain.Learns;
import org.cwnuit.train.domain.Notices;
import org.cwnuit.train.domain.RuleStime;
import org.cwnuit.train.domain.Rules;
import org.cwnuit.train.domain.Stime;
import org.cwnuit.train.domain.Sworks;
import org.cwnuit.train.domain.Trains;
import org.cwnuit.train.domain.Users;
import org.cwnuit.train.domain.Wtype;
import org.cwnuit.train.service.LearnService;
import org.cwnuit.train.service.NoticesService;
import org.cwnuit.train.service.RuleStimeService;
import org.cwnuit.train.service.RulesService;
import org.cwnuit.train.service.StimeService;
import org.cwnuit.train.service.SworksService;
import org.cwnuit.train.service.TrainsService;
import org.cwnuit.train.service.UsersService;
import org.cwnuit.train.service.WtypeService;
import org.cwnuit.train.utils.MapUtil;
import org.cwnuit.train.utils.PageModel;
import org.cwnuit.train.vo.CountVO;
import org.cwnuit.train.vo.LearnSworkRuleVO;
import org.cwnuit.train.vo.NavVO;
import org.cwnuit.train.vo.SworkRuleVO;

import com.sun.org.apache.bcel.internal.generic.NEW;

@SuppressWarnings("all")
public class CommonAction extends HttpServlet {
	RulesService rulesService = new RulesService();
	TrainsService trainsServices = new TrainsService();
	SworksService sworkService = new SworksService();
	LearnService learnServices = new LearnService();
	NoticesService noticeServices = new NoticesService();
	UsersService usersService = new UsersService();
	WtypeService wtypeService = new WtypeService();
	StimeService stimeService = new StimeService();
	RuleStimeService ruleStimeService = new RuleStimeService();

	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String cmd = request.getParameter("cmd");
		Users user = (Users) request.getSession().getAttribute("manager");
		int urole = user.getUrole();

		if (cmd.equals("left")) {// 左边树状结构展示
			String tid = request.getParameter("tid");
			String linkString = "common/left.jsp";
			if (urole == 0 || urole == 1 || urole == 2) {
				request.setAttribute("navlist", rulesService.findNav());
				List<Trains> trainslist = listTrain(request);
				request.setAttribute("trains", trainslist);
				if (tid.equals("0")) {
					if(trainslist.size()!=0){
						request.setAttribute("number", ((Trains) trainslist.get(0))
								.getTid());
					}
					else{
						request.setAttribute("number", 0);
					}
					
				} else {
					request.setAttribute("number", tid);
				}
			} else if (urole == 3 || urole == 4) {
				request.setAttribute("navlist", rulesService.findNav());
				request.setAttribute("number", ((Users) request.getSession()
						.getAttribute("manager")).getTid());
			} else if (urole == 5) {// 学习的左边导航
				request.setAttribute("number", ((Users) request.getSession()
						.getAttribute("manager")).getTid());
				request.setAttribute("rulelist", findLearn(user));
				request.setAttribute("rulelistready", findLearnReady(user));
				linkString = "common/left_learn.jsp";
			}

			request.getRequestDispatcher(linkString).forward(request, response);
		} else if (cmd.equals("listtree")) {
			request.setAttribute("navlist", rulesService.findNav());
			request.setAttribute("content_tittle", "《站细》目录");
			request.getRequestDispatcher("web/rules/list_tree.jsp").forward(request, response);
		} else if (cmd.equals("reader")) {// 阅读页面的展示
			int tid = Integer.parseInt(request.getParameter("tid"));
			request.setAttribute("tid", tid);
			request.setAttribute("cankaotrain", trainsServices.findTrain("SELECT * FROM Trains WHERE tid = " + tid));
			int tstate = findTrain(tid).getTstate();
			int shTstate = findTrain(tid).getShtstate();
			String linkStr = power(urole);
			
			SworkRuleVO lsrvoSworkRule = readRuleSwork(request);
			// 用户的角色 （0：超级管理员 、1：段长组 、2：审核组、3：车站组、4、公共用户、 5：职名学习）
			// 车站状态【0：未提交】【1：未审核】【2:已审核】【3:未通过】
			if (urole == 4 || urole == 5) {
				if (tstate != 2) {
					linkStr = "web/learn/tishi.jsp";
				} else {
					request.setAttribute("rulesworklearn",
							readRuleSworkLearn(request));
				}
			} else if (urole == 3) {
				request.setAttribute("rulesworklearn", lsrvoSworkRule);
			} else if (urole == 2){
				if (tstate == 0) {
					linkStr = "web/trains/tishi.jsp";
				} else {
					request.setAttribute("rulesworklearn",lsrvoSworkRule);
					request.setAttribute("trainwww",findTrain(tid));
				}
			} else if (urole == 1){
				if (tstate == 0) {
					linkStr = "web/trains/tishi.jsp";
				} else if (shTstate == 0){
					linkStr = "web/trains/shtishi.jsp";
				} else {
					request.setAttribute("rulesworklearn",lsrvoSworkRule);
				}
			} else {
				request.setAttribute("rulesworklearn",lsrvoSworkRule);
			}
			request.setAttribute("tstate", tstate);
			request.getRequestDispatcher(linkStr).forward(request, response);
		} else if (cmd.equals("page")) {// 上一页下一页，有点重复
			int tid = Integer.parseInt(request.getParameter("tid"));
			request.setAttribute("rulesworklearn", pageRuleSwork(request));
			String linkStr = power(urole);
			request.setAttribute("tid", tid);
			request.setAttribute("tstate", findTrain(tid).getTstate());
			request.getRequestDispatcher(linkStr).forward(request, response);
		} else if (cmd.equals("page_learn")) {// 上一页下一页，有点重复
			request.setAttribute("rulesworklearn", pageRuleSworkLearn(request));
			String linkStr = power(urole);
			request.getRequestDispatcher(linkStr).forward(request, response);
		} else if (cmd.equals("let_bottom")) {
			request.setAttribute("pm", listNotice(urole));
			request.setAttribute("count", getCount(user, request));
			request.getRequestDispatcher("common/left_buttom.jsp").forward(
					request, response);
		}

	}

	// 查找火车站信息
	private Trains findTrain(int tid) {
		String SQL = "SELECT * FROM trains WHERE tid = " + tid;
		return trainsServices.findTrain(SQL);
	}

	// 阅读规章制度的权限
	private String power(int urole) {
		String link = null;
		if (urole == 0) {
			link = "web/trains/admin.jsp";
		} else if (urole == 1) {
			link = "web/trains/reader.jsp";
		} else if (urole == 2) {
			link = "web/sworks/shz_sh.jsp";
		} else if (urole == 3) {
			link = "web/sworks/reader.jsp";
		} else if (urole == 4) {
			link = "web/learn/reader.jsp";
		} else if (urole == 5) {
			link = "web/learn/learn.jsp";
		}
		return link;
	}

	// 车站信息
	private List<Trains> listTrain(HttpServletRequest request) {
		String SQL = "SELECT * FROM Trains WHERE tstate !=10000  ORDER BY tid ASC";
		return trainsServices.findTrains(SQL);
	}

	private PageModel listNotice(int urole) {
		String SQL = "SELECT * FROM Notices WHERE nrole like '%" + urole
				+ "%'  ORDER BY nid DESC";
		return noticeServices.findByPage(0, 5, SQL);
	}

	// 学习规章制度_徐
	private LearnSworkRuleVO readRuleSworkLearn(HttpServletRequest request) {
		LearnSworkRuleVO lsrvoLearnSworkRuleVO = new LearnSworkRuleVO();
		Learns learn = null;
		Sworks sworks = null;
		Rules rules = null;
		int rid = Integer.parseInt(request.getParameter("rid"));
		int tid = Integer.parseInt(request.getParameter("tid"));
		int uid = ((Users) request.getSession().getAttribute("manager"))
				.getUid();

		String SQLBace = "SELECT * FROM Rules WHERE rlevel=4 ";
		Rules first = rulesService.findRule(SQLBace
				+ " order by rid asc limit 0,1 ");
		Rules last = rulesService.findRule(SQLBace
				+ " order by rid desc limit 0,1 ");

		rules = rulesService.findRule("SELECT * FROM Rules WHERE rid = " + rid);
		if (rules.getRid() == first.getRid()) {
			lsrvoLearnSworkRuleVO.setFirstLast("first");
		} else if (rules.getRid() == last.getRid()) {
			lsrvoLearnSworkRuleVO.setFirstLast("last");
		} else {
			lsrvoLearnSworkRuleVO.setFirstLast("");
		}

		sworks = sworkService.findSwork("SELECT * FROM Sworks WHERE tid = "
				+ tid + " and rid = " + rid);
		learn = learnServices.findLearn("SELECT * FROM Learns WHERE sid = "
				+ sworks.getSid() + " and uid = " + uid);
		if (learn == null) {
			learn = new Learns();
			learn.setLnum(0);
		}

		lsrvoLearnSworkRuleVO.setSwork(sworks);
		lsrvoLearnSworkRuleVO.setRule(rules);
		lsrvoLearnSworkRuleVO.setLearn(learn);

		return lsrvoLearnSworkRuleVO;
	}

	// 学习规章制度_徐上一页
	private LearnSworkRuleVO pageRuleSworkLearn(HttpServletRequest request) {
		LearnSworkRuleVO lsrvoLearnSworkRuleVO = new LearnSworkRuleVO();
		Learns learn = null;
		Sworks sworks = null;
		Rules rules = null;
		int rid = Integer.parseInt(request.getParameter("rid"));
		int tid = Integer.parseInt(request.getParameter("tid"));
		int uid = ((Users) request.getSession().getAttribute("manager"))
				.getUid();
		String action = "";
		try {
			action = request.getParameter("action");
		} catch (Exception e) {
			action = "";
		}

		String SQLBace = "SELECT * FROM Rules WHERE rlevel=4 ";
		Rules first = rulesService.findRule(SQLBace
				+ " order by rid asc limit 0,1 ");
		Rules last = rulesService.findRule(SQLBace
				+ " order by rid desc limit 0,1 ");

		String SQLRules = null;
		if (action.equals("top")) {
			SQLRules = SQLBace + " and rid < " + rid
					+ " order by rid desc limit 1 ";
		} else if (action.equals("down")) {
			SQLRules = SQLBace + " and rid > " + rid
					+ " order by rid asc limit 1 ";
		} else if (action.equals("first")) {
			SQLRules = SQLBace + " order by rid asc limit 1 ";
		} else if (action.equals("last")) {
			SQLRules = SQLBace + " order by rid desc limit 1 ";
		} else {
			SQLRules = "SELECT * FROM Rules WHERE rid = " + rid;
		}

		rules = rulesService.findRule(SQLRules);
		if (rules.getRid() == first.getRid()) {
			lsrvoLearnSworkRuleVO.setFirstLast("first");
		} else if (rules.getRid() == last.getRid()) {
			lsrvoLearnSworkRuleVO.setFirstLast("last");
		} else {
			lsrvoLearnSworkRuleVO.setFirstLast("");
		}

		sworks = sworkService.findSwork("SELECT * FROM Sworks WHERE tid = "
				+ tid + " and rid = " + rid);
		learn = learnServices.findLearn("SELECT * FROM Learns WHERE sid = "
				+ sworks.getSid() + " and uid = " + uid);
		if (learn == null) {
			learn = new Learns();
			learn.setLnum(0);
		}

		lsrvoLearnSworkRuleVO.setSwork(sworks);
		lsrvoLearnSworkRuleVO.setRule(rules);
		lsrvoLearnSworkRuleVO.setLearn(learn);

		return lsrvoLearnSworkRuleVO;
	}

	// 阅读规章制度_徐
	private SworkRuleVO readRuleSwork(HttpServletRequest request) {
		SworkRuleVO lsrvoSworkRuleVO = new SworkRuleVO();
		Learns learn = null;
		int rid = Integer.parseInt(request.getParameter("rid"));
		int tid = Integer.parseInt(request.getParameter("tid"));

		String SQLBace = "SELECT * FROM Rules WHERE rlevel=4 ";
		Rules first = rulesService.findRule(SQLBace
				+ " order by rid asc limit 0,1 ");
		Rules last = rulesService.findRule(SQLBace
				+ " order by rid desc limit 0,1 ");

		Rules rules = rulesService.findRule("SELECT * FROM Rules WHERE rid = "
				+ rid);
		if (rules.getRid() == first.getRid()) {
			lsrvoSworkRuleVO.setFirstLast("first");
		} else if (rules.getRid() == last.getRid()) {
			lsrvoSworkRuleVO.setFirstLast("last");
		} else {
			lsrvoSworkRuleVO.setFirstLast("");
		}

		Sworks sworks = sworkService
				.findSwork("SELECT * FROM Sworks WHERE tid = " + tid
						+ " and rid = " + rid);
		lsrvoSworkRuleVO.setSwork(sworks);
		lsrvoSworkRuleVO.setRule(rules);

		return lsrvoSworkRuleVO;
	}

	// 上一页下一页，有点重复
	private SworkRuleVO pageRuleSwork(HttpServletRequest request) {
		SworkRuleVO lsrvoSworkRuleVO = new SworkRuleVO();
		Learns learn = null;
		int rid = Integer.parseInt(request.getParameter("rid"));
		int tid = Integer.parseInt(request.getParameter("tid"));
		String action = request.getParameter("action");
		String SQLRules = null;

		String SQLBace = "SELECT * FROM Rules WHERE rlevel=4 ";
		Rules first = rulesService.findRule(SQLBace
				+ " order by rid asc limit 1 ");
		Rules last = rulesService.findRule(SQLBace
				+ " order by rid desc limit 1 ");

		if (action.equals("top")) {
			SQLRules = SQLBace + " and rid < " + rid
					+ " order by rid desc limit 1 ";
		} else if (action.equals("down")) {
			SQLRules = SQLBace + " and rid > " + rid
					+ " order by rid asc limit 1 ";
		} else if (action.equals("first")) {
			SQLRules = SQLBace + " order by rid asc limit 1 ";
		} else if (action.equals("last")) {
			SQLRules = SQLBace + " order by rid desc limit 1 ";
		}
		Rules rules = rulesService.findRule(SQLRules);
		if (rules.getRid() == first.getRid()) {
			lsrvoSworkRuleVO.setFirstLast("first");
		} else if (rules.getRid() == last.getRid()) {
			lsrvoSworkRuleVO.setFirstLast("last");
		} else {
			lsrvoSworkRuleVO.setFirstLast("");
		}
		String SQLSworks = "SELECT * FROM Sworks WHERE tid = " + tid
				+ " and rid = " + rules.getRid();
		Sworks sworks = sworkService.findSwork(SQLSworks);

		lsrvoSworkRuleVO.setRule(rules);
		lsrvoSworkRuleVO.setSwork(sworks);
		return lsrvoSworkRuleVO;
	}

	// 用户登录统计
	private CountVO getCount(Users user, HttpServletRequest request) {
		CountVO cvo = new CountVO();
		int tnum = trainsServices.findTrains(
				"SELECT * FROM Trains WHERE tstate!=10000").size();
		Trains t = (Trains) request.getSession().getAttribute("mtrain");
		int innum = sworkService.findSworks(
				"SELECT * FROM Sworks WHERE tid = " + t.getTid()).size();
		int pnum = usersService.findUsers("SELECT * FROM Users").size();
		int dzznshnum = sworkService.findSworks(
				"SELECT * FROM Sworks WHERE state = 1 AND sdstate = 0").size();
		int submitnum = sworkService.findSworks(
				"SELECT * FROM Sworks WHERE state = 1 AND tid = " + t.getTid())
				.size();
		int passnum = sworkService.findSworks(
				"SELECT * FROM Sworks WHERE sdstate = 1 AND ssstate = 1 AND tid = "
						+ t.getTid()).size();
		int nopassnum = sworkService.findSworks(
				"SELECT * FROM Sworks WHERE (sdstate != 1 OR ssstate != 1) AND tid = "
						+ t.getTid()).size();
		int yreadnum = learnServices.findLearns(
				"SELECT * FROM Learns WHERE uid = " + user.getUid()).size();
		cvo.setUrole(user.getUrole());// 用户角色
		cvo.setTnum(tnum);// 车站数（公共）
		cvo.setInnum(innum);// 车站录入制度数（公共）

		cvo.setPnum(pnum);// 人员数

		cvo.setDzznshnum(dzznshnum);// 待审核制度数

		cvo.setSubmitnum(submitnum);// 提交制度数
		cvo.setPassnum(passnum);// 通过制度数
		cvo.setNopassnum(nopassnum);// 未通过制度数

		cvo.setYreadnum(yreadnum);// 已阅读制度数
		cvo.setNreadnum((innum - yreadnum));// 未阅读制度数
		return cvo;

	}

	// 查询所有学习的信息
	public List<Rules> findLearn(Users user) {
		
		String SQL = "SELECT *,count(distinct rid)  FROM RuleStime WHERE sid in (SELECT sid FROM Stime WHERE sstate = 2 AND wid =" + 
		user.getWid() + ") group by rid";
		List<Rules> rules = new ArrayList();
		List<RuleStime> ruleStimes = ruleStimeService.findRuleStimes(SQL);
		
		Rules rule = null;
		for(RuleStime ruleStime:ruleStimes)
		{
			rule = rulesService.findRule("SELECT * FROM Rules WHERE rid = " + ruleStime.getRid());
			rules.add(rule);
		}
		return rules;
	}

	// 查询所有已经学习的信息
	public List<Rules> findLearnReady(Users user) {

		String SQL = "SELECT *,count(distinct rid)  FROM RuleStime WHERE sid in (SELECT sid FROM Stime WHERE sstate = 3 AND wid ="
				+ user.getWid() + ") group by rid";
		List<Rules> rules = new ArrayList();
		List<RuleStime> ruleStimes = ruleStimeService.findRuleStimes(SQL);
		Rules rule = null;
		for (RuleStime ruleStime : ruleStimes) {
			rule = rulesService.findRule("SELECT * FROM Rules WHERE rid = "
					+ ruleStime.getRid());
			rules.add(rule);
		}
		return rules;
	}
}
